/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.peersim.protocols.initializers;

import com.google.code.peersim.pastry.protocol.PastryNode;
import com.google.code.peersim.protocols.TwoDimCoordinatesProtocol;
import peersim.core.CommonState;
import peersim.core.Control;
import peersim.core.Network;
import peersim.core.Node;
import peersim.dynamics.NodeInitializer;

/**
 * This {@link Control} class is in charge of initializing {@link TwoDimCoordinatesProtocol}
 * instances randomly assigning them a bidimensional coordinate.
 * 
 * @author frusso
 * @version 0.1
 * @since 0.1
 */
public class TwoDimCoordinatesInitializer implements Control, NodeInitializer {

  /**
   * Constructor.
   *
   * @param prefix Prefix for accessing configuraiton parameters
   */
  public TwoDimCoordinatesInitializer(String prefix) {
    super();
  }

  /**
   * Iterates over all the {@link Node}s in the network and assings them all a
   * randomly generated bidimensional coordinate.
   *
   * {@inheritDoc}
   */
  @Override
  public boolean execute() {
    boolean stop = false;
    int n = Network.size();
    for (int i = 0; i < n; i++) {
      PastryNode node = (PastryNode) Network.get(i);
      assignCoordinates(node);
    }
    return stop;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void initialize(Node node) {
    PastryNode pn = (PastryNode) node;
    assignCoordinates(pn);
  }

  /**
   * {@inheritDoc}
   */
  private void assignCoordinates(PastryNode node) {
    TwoDimCoordinatesProtocol p = node.<TwoDimCoordinatesProtocol>getProximityProtocol();
    p.setX(CommonState.r.nextInt());
    p.setY(CommonState.r.nextInt());
  }
}